package com.iplant.ams.controller.dms;

import com.iplant.ams.service.DRMService;
import com.iplant.ams.service.po.ams.asset.AMSAssetInfo;
import com.iplant.ams.service.po.dms.maintenance.DMSConfiguration;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.annotation.trace.TraceAPI;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.orm.ORMUtils;
import com.iplant.base.utils.sql.orm.PoService;
import com.iplant.basic.controller.BasicController;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.ams.service.po.dms.DMSDeviceLedger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/DMSDeviceLedger")
public class DMSDeviceLedgerController extends BasicController<DMSDeviceLedger> {
    private static Logger logger = LoggerFactory.getLogger(DMSDeviceLedgerController.class);


    PoService<AMSAssetInfo> AssetInfoService;

    @Autowired
    DRMService mDRMService;

    public DMSDeviceLedgerController() {
        super(DMSDeviceLedger.class);
        AssetInfoService = ORMUtils.GetPoService(AMSAssetInfo.class);
    }


    /**
     * 新增或更新
     */
    @TraceAPI(value = "新增或更新")
    @PostMapping("/Update")
    public Object Update(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult;
        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }
            DMSDeviceLedger wDMSDeviceLedger = CloneTool.Clone(wParam.get("data"), DMSDeviceLedger.class);

            if (wDMSDeviceLedger == null || wDMSDeviceLedger.StandardModelID <= 0
                    || wDMSDeviceLedger.ModelID <= 0) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }
            AMSAssetInfo wAMSAssetInfo;
            if (wDMSDeviceLedger.AssetInfoID > 0) {
                ServiceResult<AMSAssetInfo> wAssetInfoServiceResult = AssetInfoService.SelectPO(wLoginUser, wDMSDeviceLedger.AssetInfoID, "");
                wAMSAssetInfo = wAssetInfoServiceResult.Result;
                if (StringUtils.isNotEmpty(wAssetInfoServiceResult.getFaultCode())) {
                    wResult = GetResult(RetCode.SERVER_CODE_ERR, wAssetInfoServiceResult.getFaultCode());
                    return wResult;
                }
                if (wAMSAssetInfo == null || wAMSAssetInfo.ID <= 0) {
                    wAMSAssetInfo = new AMSAssetInfo(wDMSDeviceLedger);
                } else {
                    wAMSAssetInfo.SetLedger(wDMSDeviceLedger);
                }
            } else {
                wAMSAssetInfo = new AMSAssetInfo(wDMSDeviceLedger);
            }

            wAMSAssetInfo.setUserInfo(wLoginUser);
            ServiceResult<Integer> wServiceResult = AssetInfoService.UpdatePo(wLoginUser,
                    wAMSAssetInfo);

            if (StringUtils.isNotEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
                return wResult;
            }


            wDMSDeviceLedger.setUserInfo(wLoginUser);
            wDMSDeviceLedger.AssetInfoID = wAMSAssetInfo.ID;
            wDMSDeviceLedger.Code = wAMSAssetInfo.Code;
            wServiceResult = mPoService.UpdatePo(wLoginUser, wDMSDeviceLedger);

            //同步设备构型名称
            mDRMService.DRM_SynchronizDeviceConfigurationName(wLoginUser,wDMSDeviceLedger);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wDMSDeviceLedger);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }


    /**
     * 新增或更新
     */
    @TraceAPI("批量新增或更新")
    @PostMapping("/UpdateList")
    public Object UpdateList(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult;
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // ServiceResult<List<AMSAssetStandardModel>> wServiceResult = mPoService.UpdatePoList(wLoginUser, wParam);
            //成功后插入设备型号
            //默认使用设备类型第一个激活的
            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }
            List<DMSDeviceLedger> wList = CloneTool.CloneArray(wParam.get("data"), DMSDeviceLedger.class);

            ServiceResult<Integer> wServiceResult = new ServiceResult<>();
            ServiceResult<AMSAssetInfo> wAssetInfoServiceResult;
            AMSAssetInfo wAMSAssetInfo;
            for (DMSDeviceLedger wDMSDeviceLedger : wList) {

                if (wDMSDeviceLedger == null || wDMSDeviceLedger.StandardModelID <= 0
                        || wDMSDeviceLedger.ModelID <= 0) {
                    continue;
                }
                if (wDMSDeviceLedger.AssetInfoID > 0) {
                    wAssetInfoServiceResult = AssetInfoService.SelectPO(wLoginUser, wDMSDeviceLedger.AssetInfoID, "");
                    wAMSAssetInfo = wAssetInfoServiceResult.Result;
                    if (StringUtils.isNotEmpty(wAssetInfoServiceResult.getFaultCode())) {
                        wServiceResult.FaultCode += wAssetInfoServiceResult.getFaultCode();
                        break;
                    }
                    if (wAMSAssetInfo == null || wAMSAssetInfo.ID <= 0) {
                        wAMSAssetInfo = new AMSAssetInfo(wDMSDeviceLedger);
                    } else {
                        wAMSAssetInfo.SetLedger(wDMSDeviceLedger);
                    }
                } else {
                    wAMSAssetInfo = new AMSAssetInfo(wDMSDeviceLedger);
                }
                wAMSAssetInfo.setUserInfo(wLoginUser);
                wServiceResult = AssetInfoService.UpdatePo(wLoginUser, wAMSAssetInfo);

                if (StringUtils.isNotEmpty(wServiceResult.getFaultCode())) {
                    break;
                }

                wDMSDeviceLedger.setUserInfo(wLoginUser);
                wDMSDeviceLedger.AssetInfoID = wAMSAssetInfo.ID;

                wDMSDeviceLedger.Code = wAMSAssetInfo.Code;
                wServiceResult = mPoService.UpdatePo(wLoginUser, wDMSDeviceLedger);
                if (StringUtils.isNotEmpty(wServiceResult.getFaultCode())) {
                    break;
                }
            }
            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wList, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }


    /**
     * 新增或更新
     */
    @TraceAPI("批量删除")
    @PostMapping("/DeleteList")
    public Object DeleteList(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult;
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // ServiceResult<List<AMSAssetStandardModel>> wServiceResult = mPoService.UpdatePoList(wLoginUser, wParam);
            //成功后插入设备型号
            //默认使用设备类型第一个激活的
            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }
            List<DMSDeviceLedger> wList = CloneTool.CloneArray(wParam.get("data"), DMSDeviceLedger.class);

            ServiceResult<Integer> wServiceResult = new ServiceResult<>();
            ServiceResult<AMSAssetInfo> wAssetInfoServiceResult;
            AMSAssetInfo wAMSAssetInfo;
            for (DMSDeviceLedger wDMSDeviceLedger : wList) {


                if (wDMSDeviceLedger.AssetInfoID > 0) {
                    wAssetInfoServiceResult = AssetInfoService.SelectPO(wLoginUser, wDMSDeviceLedger.AssetInfoID, "");
                    wAMSAssetInfo = wAssetInfoServiceResult.Result;
                    if (StringUtils.isNotEmpty(wAssetInfoServiceResult.getFaultCode())) {
                        wServiceResult.FaultCode += wAssetInfoServiceResult.getFaultCode();
                        break;
                    }
                    if (wAMSAssetInfo != null && wAMSAssetInfo.ID > 0) {

                        wServiceResult = AssetInfoService.DeletePO(wLoginUser, wAMSAssetInfo);
                        if (StringUtils.isNotEmpty(wServiceResult.getFaultCode())) {
                            break;
                        }
                    }
                }

                wServiceResult = mPoService.DeletePO(wLoginUser, wDMSDeviceLedger);

                if (StringUtils.isNotEmpty(wServiceResult.getFaultCode())) {
                    break;
                }

            }
            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "");
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 新增或更新
     */
    @TraceAPI("删除")
    @PostMapping("/Delete")
    public Object Delete(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult;
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // ServiceResult<List<AMSAssetStandardModel>> wServiceResult = mPoService.UpdatePoList(wLoginUser, wParam);
            //成功后插入设备型号
            //默认使用设备类型第一个激活的
            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }
            DMSDeviceLedger wDMSDeviceLedger = CloneTool.Clone(wParam.get("data"), DMSDeviceLedger.class);

            ServiceResult<Integer> wServiceResult = new ServiceResult<>();
            ServiceResult<AMSAssetInfo> wAssetInfoServiceResult;
            AMSAssetInfo wAMSAssetInfo;
            if (wDMSDeviceLedger.AssetInfoID > 0) {
                wAssetInfoServiceResult = AssetInfoService.SelectPO(wLoginUser, wDMSDeviceLedger.AssetInfoID, "");
                wAMSAssetInfo = wAssetInfoServiceResult.Result;
                if (StringUtils.isEmpty(wAssetInfoServiceResult.getFaultCode())) {

                    if (wAMSAssetInfo != null && wAMSAssetInfo.ID > 0) {

                        wServiceResult = AssetInfoService.DeletePO(wLoginUser, wAMSAssetInfo);

                    }
                }
                wServiceResult.FaultCode += wAssetInfoServiceResult.getFaultCode();
            }
            if (StringUtils.isEmpty(wServiceResult.getFaultCode()))
                wServiceResult = mPoService.DeletePO(wLoginUser, wDMSDeviceLedger);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "");
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @TraceAPI("复制内容")
    @PostMapping("/CopyContent")
    public Object CopyContent(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult;
        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (!wParam.containsKey("data") || !wParam.containsKey("target")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }
            DMSDeviceLedger wDMSDeviceLedger = CloneTool.Clone(wParam.get("data"), DMSDeviceLedger.class);

            DMSDeviceLedger wDMSDeviceLedgerTarget = CloneTool.Clone(wParam.get("target"), DMSDeviceLedger.class);

            if (wDMSDeviceLedger == null || wDMSDeviceLedger.StandardModelID <= 0
                    || wDMSDeviceLedger.ModelID <= 0 || wDMSDeviceLedgerTarget == null || wDMSDeviceLedgerTarget.StandardModelID <= 0
                    || wDMSDeviceLedgerTarget.ModelID <= 0) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            ServiceResult<List<DMSConfiguration>> wServiceResult = mDRMService.DMS_CopyDeviceConfigurationList(wLoginUser, wDMSDeviceLedger, wDMSDeviceLedgerTarget);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.getResult(), wDMSDeviceLedgerTarget);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

}
